﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Drawing;
using System.Collections;
using System.Data.SqlClient;

public partial class comment : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DBaccess db = new DBaccess();
        String getRid = HttpContext.Current.Request.QueryString["rid"];
        DataSet ds = new DataSet();
        int sid = int.Parse(Session["mid"].ToString());
        if(getRid == null)  getRid = "5";
        ds = db.GetDataSet("select * from mr_v_resource where rid='" + getRid + "'");
        LabelRid.Text = ds.Tables[0].Rows[0]["rid"].ToString();
        Image1.ImageUrl = ResolveUrl(ds.Tables[0].Rows[0]["logo"].ToString());
        LabelName.Text = "资源名：" + ds.Tables[0].Rows[0]["rname"].ToString();
        LabelCourse.Text = "所属课程：" + ds.Tables[0].Rows[0]["cname"].ToString();
        LabelOwner.Text = "拥有者：" + ds.Tables[0].Rows[0]["mname"].ToString();
        LabelScore.Text = "难度评分：" + ds.Tables[0].Rows[0]["score"].ToString();
        ResourceReco rr = new ResourceReco(sid,int.Parse(getRid));
        double diffScore =rr.GetDiffScore();
        double downloadScore = rr.GetDownloadScore();
        double preferenceScore = rr.GetPreferenceScore();
        double timeScore = rr.GetTimeScore();

        double[] yValues = {diffScore, downloadScore, preferenceScore, timeScore};
        String[] xValues = { "难度", "下载", "偏好", "热度" };
        Chart1.Series[0].Points.DataBindXY(xValues, yValues);
        this.Chart1.Series["Series1"].Points.DataBindXY(xValues, yValues);
        // Set radar chart style (Area, Line or Marker)  
        this.Chart1.Series["Series1"]["RadarDrawingStyle"] = "Area";
        // Set circular area drawing style (Circle or Polygon)  
        this.Chart1.Series["Series1"]["AreaDrawingStyle"] = "Circle";
        // Set labels style (Auto, Horizontal, Circular or Radial)  
        this.Chart1.Series["Series1"]["CircularLabelsStyle"] = "Horizontal";


        LabelReco.Text = "推荐度：" + rr.GetAll().ToString("0.00");
        LabelReco.Font.Bold = true;
        LabelUptime.Text = "上传时间：" + ((DateTime)ds.Tables[0].Rows[0]["upload_time"]).ToLongDateString();
        LabIntro.Text = "简介：" + ds.Tables[0].Rows[0]["introduction"].ToString();
        LabKeyword.Text = "关键词：" + ds.Tables[0].Rows[0]["keyword"].ToString();
        LabReason0.Text = "难度适合度（" + diffScore.ToString("0.00") + "%)";
        LabReason1.Text = "历史下载数（" + downloadScore.ToString("0.00") + "%）";
        LabReason2.Text = "用户历史偏好（" +preferenceScore.ToString("0.00") + "%）";
        LabReason3.Text = "热度推荐（" + timeScore.ToString("0.00") + "%)";
        LabReasonText.Text = "推荐理由：";
        ButtonComment.Attributes["onclick"] = "AlertHello()";
        if (diffScore > 90)
        {
            LabReason0.ForeColor = Color.Red;
            LabReason0.Font.Bold = true;
            LabReasonText.Text += "难度适合你！";
        }
        if (downloadScore > 90)
        {
            LabReason1.ForeColor = Color.Red;
            LabReason1.Font.Bold = true;
            LabReasonText.Text += "大家都爱它！";
        }
        if (preferenceScore > 90)
        {
            LabReason2.ForeColor = Color.Red;
            LabReason2.Font.Bold = true;
            LabReasonText.Text += "你就喜欢这型的！";
        }
        if (timeScore > 90)
        {
            LabReason3.ForeColor = Color.Red;
            LabReason3.Font.Bold = true;
            LabReasonText.Text += "上传者极力推荐！";
        }
        if (LabReasonText.Text == "推荐理由：") LabReasonText.Text = "推荐理由：没啥特殊的。";
        HyperLinkRecentComment.Text = "最新评论(" + ds.Tables[0].Rows.Count.ToString() + ")";
        HyperLinkRecentComment.NavigateUrl = "~/recentcomment.aspx";
        HyperLinkRecentComment.ForeColor = Color.Blue;
        ds = db.GetDataSet("select * from mr_v_download where time > (select last_download_time from mr_member where mid ='" + sid + "')");
        HyperLinkRecentDownload.Text = "最新下载(" + ds.Tables[0].Rows.Count.ToString() + ")";
        HyperLinkRecentDownload.NavigateUrl = "~/recentdownload.aspx";
        HyperLinkRecentDownload.ForeColor = Color.Blue;
        if (!IsPostBack)
        {
            SetTop(0);
        }
        string lasttime;
        SqlDataReader last_logn_time = db.GetReader("select last_resource_time from mr_member where mid = '" + Session["mid"].ToString() + "'");
        if (last_logn_time.Read())
        {
            lasttime = last_logn_time.GetValue(0).ToString();
            SqlDataReader count = db.GetReader("select count(*) from mr_resource where upload_time >'" + lasttime + "'");
            if (count.Read())
            {
                HyperLink24.Text = "最新资源（" + count.GetValue(0).ToString() + "）";
            }
            else
                HyperLink24.Text = "最新资源（0）";
        }
    }

    protected void ButtonComment_Click(object sender, EventArgs e)
    {
        DBaccess db = new DBaccess();
        String getRid = HttpContext.Current.Request.QueryString["rid"];
        int results = 0;
        results = db.ExecSql("insert into mr_comment(sid, rid, comment, time) values (" + Session["mid"] + "," + getRid + "," + TextBox1.Text + "," + DateTime.Now + ")");
        if(results > 0)
            Response.Write("<script>alert('评论成功!');</script>");
        else
            Response.Write("<script>alert('评论失败!');</script>");
    }
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        String rname = LabelRid.Text;
        DBaccess db = new DBaccess();
        string sql = "select score from mr_student where sid='" + Session["mid"].ToString() + "'";
        string sql1 = "select score from mr_resource where rid='" + rname + "'";
        SqlDataReader read1 = db.GetReader(sql1);
        SqlDataReader read = db.GetReader(sql);
        read.Read();
        read1.Read();
        if (int.Parse(read.GetValue(0).ToString()) >= int.Parse(read1.GetValue(0).ToString()))
        {

            SqlDataReader path = db.GetReader("select rid,resource from mr_resource where rid = '" + rname + "'");
            path.Read();
            string filename = System.IO.Path.GetFileName((string)path.GetValue(1));
            Response.Clear();
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
            Response.WriteFile((string)path.GetValue(1));
            Response.Flush();
            Response.Close();
            string time = DateTime.Now.ToString();
            string sql2 = "insert into mr_download(sid,rid,time) values('" + Session["mid"].ToString() + "','" + rname + "','" + time + "')";
            SqlDataReader read2 = db.GetReader("select score from mr_resource where rid='" + rname + "'");
            read2.Read();
            string score = read2.GetValue(0).ToString();
            string sql3 = "update mr_student set score=score-'" + score + "' where sid='" + Session["mid"].ToString() + "'";
            db.ExecSql(sql2);
            db.ExecSql(sql3);
        }
        else
            Response.Redirect("你的积分不足，请充值！");
    }
    protected void Button3_Click(object sender, EventArgs e)
    {

    }
    protected void ButtonUpdate_Click(object sender, EventArgs e)
    {
        DBaccess db = new DBaccess();
        String getRid = HttpContext.Current.Request.QueryString["rid"];
        int results = 0;
        String sql = "update mr_resource set upload_time = '" + System.DateTime.Now + "' where rid = '" + getRid + "'";
        results = db.ExecSql(sql);
        if (results > 0)
            Response.Write("<script>alert('推送成功!');</script>");
        else
            Response.Write("<script>alert('推送失败!');</script>");
    }
    public void SetTop(int tag)
    {
        DBaccess db = new DBaccess();
        DataSet ds = new DataSet();
        String tablename = "mr_test";
        String condition = "";
        DateTime currentTime = new DateTime();
        currentTime = DateTime.Now;
        if (tag == 0)
        {
            tablename = "mr_v_downloadcount";
            LabelTitle.Text = "总排行榜";
        }
        else if (tag == 1)
        {
            tablename = "mr_v_downloadcount_month ";
            condition = "where year = '" + currentTime.Year.ToString() + "' and month = '" + (currentTime.Month - 1).ToString() + "'";
            LabelTitle.Text = "月排行榜";
        }
        else if (tag == 2)
        {
            tablename = "mr_v_downloadcount_year ";
            condition = "where year = '" + currentTime.Year.ToString() + "'";
            LabelTitle.Text = "年排行榜";
        }
        ds = db.GetDataSet("select top 5 * from " + tablename + condition + "  order by num desc");
        HyperLinkRank1.Text = ds.Tables[0].Rows[0]["rname"].ToString();
        HyperLinkRank1.NavigateUrl = "~/comment.aspx?rid=" + ds.Tables[0].Rows[0]["rid"].ToString();
        LabelCount1.Text = ds.Tables[0].Rows[0]["num"].ToString();
        HyperLinkRank2.Text = ds.Tables[0].Rows[1]["rname"].ToString();
        HyperLinkRank2.NavigateUrl = "~/comment.aspx?rid=" + ds.Tables[0].Rows[0]["rid"].ToString();
        LabelCount2.Text = ds.Tables[0].Rows[1]["num"].ToString();
        HyperLinkRank3.Text = ds.Tables[0].Rows[2]["rname"].ToString();
        HyperLinkRank3.NavigateUrl = "~/comment.aspx?rid=" + ds.Tables[0].Rows[0]["rid"].ToString();
        LabelCount3.Text = ds.Tables[0].Rows[2]["num"].ToString();
        HyperLinkRank4.Text = ds.Tables[0].Rows[3]["rname"].ToString();
        HyperLinkRank4.NavigateUrl = "~/comment.aspx?rid=" + ds.Tables[0].Rows[0]["rid"].ToString();
        LabelCount4.Text = ds.Tables[0].Rows[3]["num"].ToString();
        HyperLinkRank5.Text = ds.Tables[0].Rows[4]["rname"].ToString();
        HyperLinkRank5.NavigateUrl = "~/comment.aspx?rid=" + ds.Tables[0].Rows[0]["rid"].ToString();
        LabelCount5.Text = ds.Tables[0].Rows[4]["num"].ToString();
    }
    protected void ButtonMonth_Click(object sender, EventArgs e)
    {
        SetTop(1);
    }
    protected void ButtonYear_Click(object sender, EventArgs e)
    {
        SetTop(2);
    }
    protected void ButtonAll_Click1(object sender, EventArgs e)
    {
        SetTop(0);
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        Session["search"] = TextBox2.Text;
        Response.Redirect("./Student/Search.aspx");
    }
}